package cn.mengfly.testnrz.curator;

import cn.mengfly.testnrz.im.client.FutureTaskSchedule;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.junit.Test;

import java.util.concurrent.CountDownLatch;

public class ZkLockTester {

    // 需要用锁来包含的公共资源
    int count = 0;

    @Test
    public void testLock() {
        CountDownLatch latch = new CountDownLatch(10);
        for (int i = 0; i < 10; i++) {
            ZkLock lock = new ZkLock();
            FutureTaskSchedule.add(() -> {
                lock.lock();
                for (int j = 0; j < 10; j++) {
                    count++;
                }
                try {
                    Thread.sleep(1000);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                System.out.println("count = " + count);
                // 释放锁
                lock.unlock();
                latch.countDown();
            });
        }
        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        ZkClient.inst().close();
        System.out.println("count Is " + count);
    }

    @Test
    public void testZkMutex() {
        final CuratorFramework client = ZkClient.inst().getClient();

        CountDownLatch latch = new CountDownLatch(10);
        InterProcessMutex zkMutex = new InterProcessMutex(client, "/mutex");
        for (int i = 0; i < 10; i++) {
            FutureTaskSchedule.add(() -> {
                try {
                    zkMutex.acquire();
                    for (int j = 0; j < 10; j++) {
                        count++;
                    }
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("count is " + count);
                    latch.countDown();
                    zkMutex.release();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
        }

        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("count is " + count);
    }

}
